<?php
/**
 * Geocontexter
 * @link http://code.google.com/p/geocontexter/
 * @package Geocontexter
 */

/**
 * Json Record Update controller for general data entry form
 *
 *
 * @package Geocontexter
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @author Armand Turpel <geocontexter@gmail.com>
 * @version $Rev$ / $LastChangedDate$ / $LastChangedBy$
 */

namespace Gospecies\Controller;

use Zend\View\Model\JsonModel;
use Gospecies\Controller\AbstractIdentityController;


class JsonRecordUpdateController extends AbstractIdentityJsonController
{
    public function indexAction()
    {
        // get logged user
        $this->user = $this->get_identity();

        $images = $this->request->getPost()->images;

        $media_folder_hash = '';

        if (isset($images) && (count($images) > 0)) {
            $media_folder_hash = md5(time() . uniqid('',true));
        }

        $id_attribute_group = $this->request->getPost()->id_attribute_group;

        $error = array();

        $id_record = (int)$this->request->getPost()->id_record;

        $RecordGet = $this->CoreModel('RecordGet');

        $params    = array('id_record'       => (string)$id_record,
                           'geometry_column' => 'point');

        $record    = $RecordGet->run( $params );

        if ($record instanceof \Core\Library\Exception) {
            return new JsonModel(array('error' => $record->getTraceAsString()));
        }

        // check permission if id_group is "contributor" or above.
        // users of those groups can only update own records
        //
        if ((isset($this->user->id_group) && ((int)$this->user->id_status == 200))) {
            if ((int)$this->user->id_group >= 300) {
                if ($this->user->id_user !== $record['id_owner']) {
                    return new JsonModel(array('error' => 'permission denied'));
                }
            }
        } else {
            return new JsonModel(array('error' => 'permission denied'));
        }

        $params = array('id_record' => $id_record,
                        'data'      => array('id_item'            => $this->request->getPost()->id_item,
                                             'id_project'         => $this->request->getPost()->id_project,
                                             'id_modifier'        => $this->get_identity()->id_user,
                                             'id_attribute_group' => $id_attribute_group,
                                             'id_status'          => 1000,
                                             'date_record_start'  => $this->request->getPost()->date_record_start,
                                             'date_record_end'    => $this->request->getPost()->date_record_end,
                                             'media_folder_hash'  => $media_folder_hash
                       ));

        if ($params['data']['id_item'] === null) {
            $error[] = 'id_item isnt defined';
        }

        if ($params['data']['date_record_start'] === null) {
            $error[] = 'date_record_start isnt defined';
        }

        if ($params['data']['date_record_end'] === null) {
            $error[] = 'date_record_end isnt defined';
        }

        $geometry = $this->request->getPost()->geom;

        if (false !== strstr($geometry, ',')) {
            $_geom = explode(',', $geometry);
        } elseif (false !== strstr($geometry, ' ')) {
            $_geom = explode(' ', $geometry);
        } else {
            $error[] = 'Latitude/Longitude isnt separated by space or comma.';
        }

        if (!isset($_geom[0]) || !isset($_geom[1])) {
            $error[] = 'Geographic reference is wrong';
        } else {
            $params['geom_point'] = $this->build_geometry(trim($_geom[0]), trim($_geom[1]));
        }

        $attributes = $this->request->getPost()->attributes;

        if (is_array($attributes) && (count($attributes) > 0 )) {

            $AttributeHstoreEncode = $this->CoreModel('AttributeHstoreEncode2');

            $_attributes = array();

            foreach ($attributes as $attr) {
              if (is_array($attr) && isset($attr['name']) && isset($attr['value'])) {
                $_attributes[$attr['name']] = $attr['value'];
              }
            }

            $serialized_attributes     = $AttributeHstoreEncode->encode( $id_attribute_group, $_attributes, '$$' );
       // die(var_export($serialized_attributes,true));
            $params['data']['attribute_value'] = $serialized_attributes['hstore'];
        }

        if (count($error) > 0) {
            return new JsonModel(array('error' => $error));
        }

        $RecordUpdate = $this->CoreModel('RecordUpdate');

        try {

            $update_result  = $RecordUpdate->run( $params );

            if (!empty($media_folder_hash)) {

                $tmp_image_path = $this->sessionOffsetGet('tmp_image_path');

                $RecordImageAdd    = $this->CoreModel('RecordImageAdd');
                $RecordImageUpdate = $this->CoreModel('RecordImageUpdate');

                if (!is_dir(GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $media_folder_hash)) {
                    mkdir(GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $media_folder_hash);
                    mkdir(GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $media_folder_hash . '/image');
                    mkdir(GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $media_folder_hash . '/image/thumbnail');
                }

                $tmp_folder = GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path;

                $x = 0;

                foreach ($images['i_name'] as $img) {

                    if (!empty($id_media = trim($images['i_id_media'][$x]))) {

                        $params = array('id_media'    => $id_media,
                                        'data' => array('title'           => $images['i_title'][$x],
                                                        'description'     => $images['i_description'][$x],
                                                        'preferred_order' => $x
                                        ));

                        $RecordImageUpdate->run($params);

                    } else {

                        $info = getimagesize ( $tmp_folder . '/' . $img );

                        $params = array('id_record'       => $id_record,
                                        'title'           => $images['i_title'][$x],
                                        'preferred_order' => $x,
                                        'description'     => $images['i_description'][$x],
                                        'media'           => array('file_name'   => $img,
                                                               'file_mime'       => $info['mime'],
                                                               'file_width'      => $info[0],
                                                               'file_height'     => $info[1],
                                                               'file_size'       => filesize($tmp_folder . '/' . $img))
                                        );

                        $RecordImageAdd->run($params);

                    }

                    $x++;
                }

                $RecordImageUpload = $this->CoreModel('RecordImageUpload');


                $params  = array('image_folder_path'        => GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $update_result['media_folder_hash'] . '/image',
                                 'source_image_folder_path' => GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path,
                                 'delete_source'            => true
                                );

                $result  = $RecordImageUpload->run( $params );

            } elseif (!empty($update_result['media_folder_hash'])) {

                // delete possible images

                $this->delete_source(GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $update_result['media_folder_hash'] . '/image');
                $this->delete_source(GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path);

            }

            return new JsonModel(array('result' => array('id_record' => $id_record)));

        } catch (\Exception $e) {

            $this->default_error = "Error\n File: " . __file__ . "\nLine: " . __line__ . "\nError: " . $e->__toString();


            return new JsonModel(array('error' => $this->default_error));

        }
    }
    private function build_geometry($latitude, $longitude)
    {
        return "ST_GeometryFromText('POINT({$longitude} {$latitude})',4326)";
    }

    public function imageAddAction()
    {
        require(GEOCONTEXTER_ROOT . '/public/library/jQuery-File-Upload/GospeciesUploadHandler.php');

        if (true === $this->sessionOffsetExists('tmp_image_path')) {

            $tmp_image_path = $this->sessionOffsetGet('tmp_image_path');

        } else {

            $tmp_image_path = md5(time() . rand());
            mkdir(GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path);
            $this->sessionOffsetSet('tmp_image_path', $tmp_image_path);

        }

        $options = array('upload_dir'        => GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path . '/',
                         'upload_url'        => $this->getBaseUrl().'/data/tmpuploads/' . $tmp_image_path . '/',
                         'image_folder_name' => $tmp_image_path);

        $upload_handler = new \UploadHandler($options);
        exit;
    }

    public function imageRemoveAction()
    {

        $id_media = $this->request->getPost()->id_media;

        $RecordMediaDelete = $this->CoreModel('RecordMediaDelete');

        $params  = array('id_media' => $id_media);

        $result = $RecordMediaDelete->run( $params );

        die(json_encode(array('success' => true,
                              'media'   => $result)));
    }

    /**
     * upload lists backup file for import
     */
    public function move_images($source, $dest)
    {
        foreach (
         $iterator = new \RecursiveIteratorIterator(
          new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS),
          \RecursiveIteratorIterator::SELF_FIRST) as $item
        ) {
          if ($item->isDir() && !is_dir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName())) {
            mkdir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
          } else {
            copy($item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
          }
        }
    }

    public static function delete_source($dir) {
        $iterator = new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS);
        foreach (new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::CHILD_FIRST) as $file) {
              if (!$file->isDir()) {
                 unlink($file->getPathname());
              }
        }
    }

}
